import React, { useMemo } from 'react';
import { Empty, Tooltip } from 'antd';
import moment from 'moment';
import SummaryTable from '@/components/SummaryTable';
import IconPro from '@/components/IconPro';
import SupervisorProfileGroup from './SupervisorProfileGroup';
import styles from './index.less';

const numberFixed2 = number => Math.round(number * 100) / 100;

const totalDataStrRender = (fastData, lastData) =>
    [fastData, lastData].filter(item => item !== undefined && item !== null).join('/');

const abnormalDataRender = (mine, avg, isReverseCompare = false) => {
    const compareResult = isReverseCompare ? Number(mine) < Number(avg) : Number(mine) > Number(avg);
    const abnormalData = compareResult ? <strong style={{ color: '#ffa22d' }}>{mine}</strong> : mine;
    return (
        <>
            <span style={{ whiteSpace: 'break-spaces' }}>
                {abnormalData}
                {avg !== undefined && avg !== null ? `/${numberFixed2(avg)}` : ''}
            </span>
        </>
    );
};

/**
 * 转换考勤数据
 * @param originData
 * 因为考勤数据后期可能会有新增数据, 为了适应变化, 数据结构有特殊处理.
 * 各指标信息都放入在 summaryCountItemAnalyseVos 一个对象数组里, 通过 code 做区分
 */
const transformAttendanceData = originData => {
    if (!originData || originData.length === 0) {
        return null;
    }
    // 提取指标数据, 假设所有数据的 summaryCountItemAnalyseVos 长度和结构都一样
    const indicatorMap = originData[0]?.summaryCountItemAnalyseVos.map(item => ({
        code: item.code,
        codeName: item.codeName
    }));
    const indicatorCodes = indicatorMap.map(item => item.code);
    const indicatorCodeNames = indicatorMap.map(item => item.codeName);
    // 转换字段
    const transformedData = originData.map(item => {
        const result = {
            id: item.id,
            userNo: item.userNo,
            employeeCode: item.employeeCode,
            employedName: item.employedName,
            companyCode: item.companyCode,
            departmentCode: item.departmentCode,
            departmentName: item.departmentName,
            yearMonth: item.yearMonth,
            startDate: item.startDate,
            endDate: item.endDate,
            attendanceDay: item.attendanceDay,
            actualAttendanceDay: item.actualAttendanceDay,
            entryTime: item.entryTime,
            separationTime: item.separationTime,
            month: `${moment(item.yearMonth).format('MM')}月`
        };

        if (item.summaryCountItemAnalyseVos?.length) {
            item.summaryCountItemAnalyseVos.forEach(data => {
                result[`${data.code}_countNum`] = data.countNum;
                result[`${data.code}_sumItemValue`] = data.sumItemValue;
                result[`${data.code}_averageCountNum`] = data.averageCountNum;
                result[`${data.code}_averageSumItemValue`] = data.averageSumItemValue;
            });
        }

        return result;
    });
    // 存储统计数据
    const total = {};
    // 统计数据
    transformedData.forEach(item => {
        Object.keys(item).forEach(field => {
            if (
                [
                    'month',
                    'id',
                    'userNo',
                    'employeeCode',
                    'employedName',
                    'companyCode',
                    'departmentCode',
                    'departmentName',
                    'yearMonth',
                    'startDate',
                    'endDate',
                    'attendanceDay',
                    'actualAttendanceDay',
                    'entryTime',
                    'separationTime'
                ].indexOf(field) === -1
            ) {
                if (!total[field]) {
                    total[field] = 0;
                }
                total[field] += item[field];
            }
        });
    });
    Object.keys(total).forEach(key => {
        if (key !== 'turnOut_sumItemValue' && key !== 'turnOut_averageSumItemValue') {
            total[key] = numberFixed2(total[key]);
        }
    });
    // 特殊处理, 出勤率要取平均数
    if (total.turnOut_sumItemValue) {
        total.turnOut_sumItemValue = numberFixed2(`${total.turnOut_sumItemValue / transformedData.length}`);
    }
    if (total.turnOut_averageSumItemValue) {
        total.turnOut_averageSumItemValue = numberFixed2(
            `${total.turnOut_averageSumItemValue / transformedData.length}`
        );
    }

    return {
        indicatorMap,
        indicatorCodes,
        indicatorCodeNames,
        transformedData,
        total
    };
};

// 考勤表格配置
const columns = [
    {
        title: '月份',
        dataIndex: 'month',
        key: 'month',
        align: 'center',
        width: 100
    },
    {
        title: (
            <>
                出勤率（%）
                <Tooltip
                    placement="top"
                    title="出勤率 = 应出勤分钟数-请假分钟数-迟到分钟数-早退分钟数-缺卡次数*30-缺勤次数*480/应出勤分钟数/部门平均值"
                >
                    <IconPro.Button dark icon="question-circle" />
                </Tooltip>
            </>
        ),
        key: 'attendanceRate',
        dataIndex: 'attendanceRate',
        width: 150,
        render: (text, record) => {
            if (record.$$isSummary) {
                return record.attendanceRate.props.children;
            }
            return totalDataStrRender(record.turnOut_sumItemValue, record.turnOut_averageSumItemValue);
        }
    },
    {
        title: '迟到',
        align: 'center',
        children: [
            {
                title: '次数',
                key: 'overdueNum',
                dataIndex: 'overdueNum',
                align: 'center',
                width: 110,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.overdueNum.props.children;
                    }
                    return totalDataStrRender(record.lateOne_countNum, record.lateOne_averageCountNum);
                }
            },
            {
                title: '总时长(分钟)',
                key: 'overdueTimeTotal',
                dataIndex: 'overdueTimeTotal',
                align: 'center',
                width: 140,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.overdueTimeTotal.props.children;
                    }
                    return totalDataStrRender(record.lateOne_sumItemValue, record.lateOne_averageSumItemValue);
                }
            }
        ]
    },
    {
        title: '早退',
        align: 'center',
        children: [
            {
                title: '次数',
                key: 'leaveEarlyNum',
                dataIndex: 'leaveEarlyNum',
                align: 'center',
                width: 110,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.leaveEarlyNum.props.children;
                    }
                    return totalDataStrRender(record.earlyOne_countNum, record.earlyOne_averageCountNum);
                }
            },
            {
                title: '总时长(分钟)',
                key: 'leaveEarlyTimeTotal',
                dataIndex: 'leaveEarlyTimeTotal',
                align: 'center',
                width: 140,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.leaveEarlyTimeTotal.props.children;
                    }
                    return totalDataStrRender(record.earlyOne_sumItemValue, record.earlyOne_averageSumItemValue);
                }
            }
        ]
    },
    {
        title: '缺勤',
        align: 'center',
        children: [
            {
                title: '次数',
                key: 'absenteeismNum',
                dataIndex: 'absenteeismNum',
                align: 'center',
                width: 110,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.absenteeismNum.props.children;
                    }
                    return totalDataStrRender(record.absence_countNum, record.absence_averageCountNum);
                }
            },
            {
                title: '总时长(分钟)',
                key: 'absenteeismTimeTotal',
                dataIndex: 'absenteeismTimeTotal',
                align: 'center',
                width: 140,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.absenteeismTimeTotal.props.children;
                    }
                    return totalDataStrRender(record.absence_sumItemValue, record.absence_averageSumItemValue);
                }
            }
        ]
    },
    {
        title: '缺卡',
        align: 'center',
        children: [
            {
                title: '次数',
                key: 'lackOfCardNum',
                dataIndex: 'lackOfCardNum',
                align: 'center',
                width: 110,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.lackOfCardNum.props.children;
                    }
                    return totalDataStrRender(record.lackCard_countNum, record.lackCard_averageCountNum);
                }
            }
        ]
    },
    {
        title: '请假',
        align: 'center',
        children: [
            {
                title: '总时长(小时)',
                key: 'leaveTotal',
                dataIndex: 'leaveTotal',
                align: 'center',
                width: 140,
                render: (text, record) => {
                    if (record.$$isSummary) {
                        return record.leaveTotal.props.children;
                    }
                    return totalDataStrRender(record.leave_sumItemValue, record.leave_averageSumItemValue);
                }
            }
        ]
    }
];

const Wrapper = ({ withTitle = true, children }) => {
    if (!withTitle) {
        return children;
    }
    return (
        <SupervisorProfileGroup
            title={
                <>
                    考勤情况&nbsp;
                    <Tooltip
                        placement="top"
                        title={
                            <>
                                <div>月份数据：员工个人值/部门平均值</div>
                                <div>总计：员工累计值/部门平均累计值</div>
                                <div>总计中标红数据为较差于平均值</div>
                            </>
                        }
                    >
                        <IconPro.Button dark icon="question-circle" />
                    </Tooltip>
                </>
            }
        >
            {children}
        </SupervisorProfileGroup>
    );
};

/**
 * 工作任务
 */
const GroupingOfCourse = props => {
    const { data, withTitle } = props;
    // 获取工作任务数据
    const attendanceData = useMemo(() => transformAttendanceData(data.attendanceData), [JSON.stringify(data)]);

    const {
        absence_averageCountNum,
        absence_averageSumItemValue,
        absence_countNum,
        absence_sumItemValue,
        earlyOne_averageCountNum,
        earlyOne_averageSumItemValue,
        earlyOne_countNum,
        earlyOne_sumItemValue,
        lackCard_averageCountNum,
        lackCard_countNum,
        lateOne_averageCountNum,
        lateOne_averageSumItemValue,
        lateOne_countNum,
        lateOne_sumItemValue,
        leave_averageSumItemValue,
        leave_sumItemValue,
        turnOut_averageSumItemValue,
        turnOut_sumItemValue
    } = attendanceData?.total || {};
    // console.log('================>attendanceData?.total', attendanceData?.total);

    return (
        <Wrapper withTitle={withTitle}>
            <div>
                {attendanceData?.transformedData ? (
                    <>
                        <p>以下为该员工近一年的考勤情况：</p>
                        <SummaryTable
                            className={styles.attendanceTable}
                            bordered
                            columns={columns}
                            rowKey="startDate"
                            dataSource={attendanceData.transformedData || []}
                            pagination={false}
                            scroll={{ y: 300 }}
                            // vvForceToFit
                            vvSummaryFields={[
                                {
                                    month: '总计'
                                },
                                {
                                    attendanceRate: () =>
                                        abnormalDataRender(turnOut_sumItemValue, turnOut_averageSumItemValue, true)
                                },
                                {
                                    overdueNum: () => abnormalDataRender(lateOne_countNum, lateOne_averageCountNum)
                                },
                                {
                                    overdueTimeTotal: () =>
                                        abnormalDataRender(lateOne_sumItemValue, lateOne_averageSumItemValue)
                                },
                                {
                                    leaveEarlyNum: () => abnormalDataRender(earlyOne_countNum, earlyOne_averageCountNum)
                                },
                                {
                                    leaveEarlyTimeTotal: () =>
                                        abnormalDataRender(earlyOne_sumItemValue, earlyOne_averageSumItemValue)
                                },
                                {
                                    absenteeismNum: () => abnormalDataRender(absence_countNum, absence_averageCountNum)
                                },
                                {
                                    absenteeismTimeTotal: () =>
                                        abnormalDataRender(absence_sumItemValue, absence_averageSumItemValue)
                                },
                                {
                                    lackOfCardNum: () => abnormalDataRender(lackCard_countNum, lackCard_averageCountNum)
                                },
                                {
                                    leaveTotal: () => abnormalDataRender(leave_sumItemValue, leave_averageSumItemValue)
                                }
                            ]}
                        />
                    </>
                ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
            </div>
        </Wrapper>
    );
};

export default GroupingOfCourse;
